package com.gugee.common.web.config.exception;
import com.gugee.common.web.util.Ret;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Primary
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {RuntimeException.class, Exception.class})
    @ResponseBody
    public String handle(Exception e) {
        if(e instanceof MethodArgumentNotValidException || e instanceof ParamsException){
            log.error("请求参数有误",e);

            if(e instanceof MethodArgumentNotValidException){
                val bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
                val allErrors = bindingResult.getAllErrors();
                return Ret.err(allErrors.get(0).getDefaultMessage());
            }

            return Ret.err("request params error");
        }
        log.error("系统错误",e);
        return Ret.err("System Error");
    }

}